import React from 'react';
import {Route,Redirect,Switch} from 'react-router-dom';
import {RouteComponentProps,useHistory} from 'react-router';
import {Iprops} from '../utils/interface';
import {getCookie} from '../utils/cookie';
const Router:React.FC<Iprops> = props =>{
    const history = useHistory()
    return <Switch>
        {
            props.routes.map((item,index)=>{
                if(item.redirect) return <Redirect key={index} from={item.path} to={item.redirect} />
                return <Route key={index} path={item.path} render={(renderProps:RouteComponentProps)=>{
                    //登录拦截
                    const {location:{pathname}} = renderProps;
                    if(!getCookie() && pathname !== '/login' && pathname !=='/main'){
                        history.replace(`/login?redirect=${encodeURIComponent(pathname)}`);
                        return
                    }
                    if(item.children) return <item.component {...renderProps} routes={item.children} />
                    return <item.component {...renderProps}/>
                }} />
            })
        }
    </Switch>
};

export default Router